<template>
  <div id="app">
    <el-dialog :visible.sync="addTalentDialog" :title="title" top="10px" center>
      <div
          style="height:calc(100vh - 250px);overflow: scroll;display: flex;flex-direction: column;align-items: center;margin-top: 15px">
        <div>
          <el-upload
              class="avatar-uploader"
              :headers="headers"
              :action="`${$apiHost}/img/fileImgUrl`"
              :show-file-list="false"
              :on-success="handleAvatar">
            <img v-if="avatarUrl" :src="'https://'+avatarUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <span>点击上传头像</span>
        <div class="content">
          <span><i style="color: red">*</i>姓名：</span>
          <el-input size="small" v-model="form.userName" style="width: 35%" :disabled="editUsrId!=''"></el-input>
          <span><i style="color: red">*</i>手机号：</span>
          <el-input size="small" v-model="form.phoneNumber" style="width: 35%" :disabled="editUsrId!=''"></el-input>
        </div>
        <div class="content">
          <span><i style="color: red">*</i>密码：</span>
          <el-input size="small" v-model="form.password" style="width: 35%" type="password" show-password :disabled="editUsrId!=''"></el-input>
          <span><i style="color: red">*</i>微信号：</span>
          <el-input size="small" v-model="form.wechatId" style="width: 35%"></el-input>
        </div>
        <div class="content">
          <span><i style="color: red">*</i>性别：</span>
          <el-select size="small" style="width: 35%" v-model="form.sex">
            <el-option value="男" label="男"></el-option>
            <el-option value="女" label="女"></el-option>
          </el-select>
          <span><i style="color: red">*</i>岗位：</span>
          <el-select size="small" style="width: 35%" v-model="form.roleId">
            <el-option v-for="item in talentRole" :value="item.roleId" :label="item.roleName"
                       :key="item.roleId"></el-option>
          </el-select>
        </div>
        <div class="content"><i style="color: red">*</i>现居地：
          <el-input style="width: 85%" v-model="form.address" :disabled="!(keyword||address)">
            <el-button slot="append" icon="el-icon-search" @click="openMapDia">打开地图</el-button>
          </el-input>
        </div>
        <div class="content">个人简介：
          <el-input style="width: 84%" v-model="form.introduction">
          </el-input>
        </div>
        <div class="content">
          <span><i style="color: red">*</i>工作年限：</span>
          <el-input size="small" v-model="form.workYears" style="width: 35%"></el-input>
          <span><i style="color: red">*</i>身份证号码：</span>
          <el-input size="small" v-model="form.idCard" style="width: 35%" :disabled="editUsrId!=''"></el-input>
        </div>
        <div class="content">
          <span><i style="color: red">*</i>身份证正面图片：</span>
          <el-upload
              class="avatar-uploader"
              :headers="headers"
              :action="`${$apiHost}/img/fileImgUrl`"
              :show-file-list="false"
              :on-success="handleChangeFont">
            <img v-if="frontImg" :src="'https://'+frontImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span style="margin-left: 20px"><i style="color: red">*</i>身份证反面图片：</span>
          <el-upload
              class="avatar-uploader"
              :headers="headers"
              :action="`${$apiHost}/img/fileImgUrl`"
              :show-file-list="false"
              :on-success="handleChangeBack">
            <img v-if="backImg" :src="'https://'+backImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="content">
          <span>技能证书：(复制粘贴即可上传图片)</span>
          <div v-for="(item,index) in certificateImg" style="display: flex">
            <el-image :src="'https://'+item"
                      :preview-src-list="['https://'+item]" style="width: 100px"></el-image>
            <div @click="deleteCer(index)" style="margin-right: 15px">
              <el-icon name="delete"></el-icon>
            </div>
          </div>
        </div>
        <div style="margin-top:30px;width: 90%">
          <span>工作经历：</span>
          <div class="content" v-for="(item,index) in projectDetail">
            <el-card class="box-card">
              <div> 开始时间：
                <el-date-picker
                    v-model="item.startTime"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    size="small"
                    placeholder="选择日期"
                >
                </el-date-picker>
                结束时间：
                <el-date-picker
                    v-model="item.endTime"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    size="small"
                    placeholder="选择日期">
                </el-date-picker>
              </div>
              <div style="margin-top: 20px">
                项目名称：
                <el-input style="width: 80%" size="small" v-model="item.projectName"></el-input>
              </div>
              <div style="margin-top: 20px">
                工作内容：
                <el-input style="width: 80%" size="small" type="textarea" v-model="item.content"></el-input>
              </div>
            </el-card>
            <i class="el-icon-delete" style="margin-left: 10px" v-if="projectDetail.length>1"
               @click="deleteExperience(index)"></i>
          </div>
        </div>
        <div>
          <el-link style="color: #303e9d;margin-top: 10px;margin-bottom: 20px" @click="addExperience(projectDetail)">
            +添加项目经历
          </el-link>
        </div>
      </div>
      <span slot="footer">
        <el-button style="color: #FFFFFF" @click="submitTalent" v-if="!editUsrId">提 交</el-button>
        <el-button style="color: #FFFFFF" @click="editTalent" v-if="editUsrId">编 辑</el-button>
        <el-button style="color: #343a40;background-color:#e0e0e0;" @click="addTalentDialog=false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="请选择地图定位"
        :visible.sync="openMap"
        :close-on-click-modal="false"
        width="70%"
    >
      <div class="mapBox">
        <div class="searchBox">
          <span>按地址搜索：</span>
          <el-input
              style="width:250px;"
              placeholder="请输入关键字"
              suffix-icon="el-icon-search"
              @input="searchByKeyword"
              @focus="searchByKeyword"
              size="medium"
              v-model="keyword">
          </el-input>
          <div class="search-result" v-if="searchResult.length && isShowResult">
            <div class="result-item" v-for="item of searchResult" :key="item.id" @click="handleClickResult(item)">
              <div class="area-name">{{ item.name }}</div>
              <div class="area-address">{{ item.district + item.address }}</div>
            </div>
          </div>
        </div>
        <div id="container" style="width: 100%;height: 400px;">
        </div>
        <div style="margin-top: 30px;">
          <el-form :inline="true" :model="loc">
            <el-form-item label="经度">
              <el-input style="width: 300px;" v-model="loc.longitude" placeholder="经度"></el-input>
            </el-form-item>
            <el-form-item label="纬度">
              <el-input style="width: 300px;" v-model="loc.latitude" placeholder="纬度"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button @click="openMap = false" style="background-color:#e0e0e0;color: #343a40">取 消</el-button>
            <el-button type="primary" @click="sureSelPoint">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  securityJsCode: '4617c699fc2723880c5f7e897eb8ec51'  //填写你的安全密钥
}

export default {
  name: "addTalent",
  components: {
    Editor,
    Toolbar
  },
  data() {
    return {
      loc: {
        longitude: '',
        latitude: ''
      },
      address: "",
      marker: null,
      autocomplete: null,
      placeSearch: null, //搜索框
      keyword: '',
      searchResult: [],
      isShowResult: false,
      certificateImg: [],
      addTalentDialog: false,
      openMap: false,
      title: "添加人才信息",
      form: {
        introduction: "暂无简介",
        userName: "",
        sex: "",
        phoneNumber: "",
        age: "",
        password: "",
        address: "",
        idCard: "",
        wechatId: "",
        roleId: "",
        workYears: "",
      },
      talentRole: [],
      upImage: [],
      upImageList: [],
      imageUrl: [],
      frontImg: '',
      AMap: null,
      map: null,
      backImg: '',
      editUsrId: '',
      avatarUrl: '',
      editor: null,
      html: '',
      toolbarConfig: {},
      mode: 'default',
      projectDetail: [
        {
          startTime: "",
          endTime: "",
          content: "",
          projectName: "",
        }
      ]
    }
  },

  computed: {
    headers() {
      const token = window.$quinn.getStorage("tokenv3")
      return {
        token,
      };
    }
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
  },
  mounted() {
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    deleteCer(i) {
      this.certificateImg.splice(i, 1)
    },
    handlePaste(event) {
      if (!this.addTalentDialog) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/img/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': window.$quinn.getStorage("tokenv3")
        }
      })
          .then(response => {
            this.certificateImg.push(response.data.result[0]);
          })
          .catch(error => {
          });
    },
    handleClick() {
      this.map.on('click', (e) => {
        let lng = e.lnglat.lng
        let lat = e.lnglat.lat
        let marker = new AMap.Marker({
          position: new AMap.LngLat(lng, lat)
        })
        this.map.clearMap()// 清除所有覆盖物（点标志）
        this.map.add(marker)// 添加点标志
        let lnglat = [lng, lat]
        let that = this
        that.geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            that.address = result.regeocode.formattedAddress;
            that.showInfoWindow(marker);//自定义信息窗体
            let thisPosition = {
              address: that.address,
              lng: lng,
              lat: lat
            };
            that.$emit("select", thisPosition)
          } else {
            that.$message.error('根据经纬度查询地址失败')
          }
        })
        this.loc.latitude = lat
        this.loc.longitude = lng
      })
    },
    showInfoWindow(marker) {
      let infoWindow = new AMap.InfoWindow({
        isCustom: true, //是否自定义信息窗体
        content: `<div style="background-color: white;padding: 0 5px; border-radius: 5px;border: 1px solid #cccccc;"> 地址：${this.address}</div>`,
        closeWhenClickMap: true,
        zIndex: 999,
        offset: new AMap.Pixel(16, -35)
      });
      infoWindow.open(this.map, marker.getPosition());
    },
    handleClickResult(e) {
      const {location, district, address} = e
      const {lng, lat} = location || {}
      // 1. 如果当前搜索结果有经纬度, 直接在地图上选中, 并返回当前的值
      if (lng && lat) {
        this.map.clearMap() //先清空点位
        this.changeValue(lng, lat, e.name, district + address)
        this.keyword = district + address
      } else {
        this.isShowResult = false
        this.placeSearch.search(district + address);
      }
    },
    // 输入框搜索显示下拉
    searchByKeyword() {
      this.autocomplete.search(this.keyword, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          this.searchResult = result.tips.map((item) => {
            return {
              ...item,
              address: Array.isArray(item.address) ? (item.address[0] || '') : item.address
            }
          })
          this.isShowResult = true
        }
      })
    },
    // // 点击地图
    // initMarket(name) {
    //   if (!(this.loc.longitude && this.loc.latitude)) {
    //     return
    //   }
    //   this.isShowResult = false
    //   if (this.map.getAllOverlays('marker').length) {
    //     // 地图已有标注，清除标注
    //     this.map.clearMap();
    //   }
    //   this.marker = new AMap.Marker({
    //     icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
    //     position: [this.loc.longitude, this.loc.latitude],
    //     offset: new AMap.Pixel(-10, -26),
    //     zIndex: 102
    //   })
    //   this.showInfoWindow(this.marker);//自定义信息窗体
    //   if (name) {
    //     let num = name.length * 4
    //     marker.value.setLabel({
    //       offset: new AMap.value.Pixel(-num, 35),
    //       content: name
    //     })
    //   }
    //   this.map.add(this.marker)
    // },
    initAMap() {
      AMapLoader.reset()
      AMapLoader.load({
        key: "eaec2470d19b92bbe95753e566dfda1d",             //Key
        version: "2.0",
        plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.MarkerClusterer', 'AMap.DistrictSearch', 'AMap.ZoomControl', 'AMap.Polygon', 'AMap.Geocoder',],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.geocoder = new AMap.Geocoder()
        this.map = new AMap.Map("container", {  //设置地图容器id
          // viewMode: "3D",    //是否为3D地图模式
          resizeEnable: true,
          zoom: 12,           //初始化地图级别
          center: [112.938814, 28.228209], //初始化地图中心点位置
        });
        this.handleClick(AMap)//地图选点
        // this.map.on('click', (e) => {
        //   this.loc.latitude = e.lnglat.lat
        //   this.loc.longitude = e.lnglat.lng
        //   this.initMarket()
        // })
        var autoOptions = {
          input: "tipinput"
        };
        this.autocomplete = new AMap.AutoComplete(autoOptions);
        this.placeSearch = new AMap.PlaceSearch({
          map: this.map
        });
      }).catch(e => {
        // console.log(e);
      })
    },
    changeValue(longitude, latitude, name, address) {
      this.isShowResult = false
      this.loc.longitude = longitude
      this.loc.latitude = latitude
      const center = new AMap.LngLat(longitude, latitude);
      // 将地图的中心点移动到指定的经纬度
      this.map.setCenter(center);
      this.marker = new AMap.Marker({
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        position: [this.loc.longitude, this.loc.latitude],
        zIndex: 103
      })
      this.map.add(this.marker)
    },
    sureSelPoint() {
      if (this.loc.latitude && this.loc.longitude) {
        this.openMap = false
        this.form = {...this.form, address: this.address || this.keyword};
      } else {
        this.$message.warning('请选择经纬度')
      }
    },
    onSuccess(res) {
      if (res.code == 200 && res.result) {
        this.certificateImg = res.result[0];
        // console.log(this.certificateImg)
      }
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    handleOpen(row) {
      this.addTalentDialog = true
      this.$api.talentGetRoleId().then(res => {
        this.talentRole = res
      })
      this.form = this.$options.data(this).form
      this.frontImg = ""
      this.backImg = ""
      this.avatarUrl = ""
      this.certificateImg = []
      this.projectDetail = []
      this.loc.longitude=""
      this.loc.latitude=""
      if (row) {
        this.editUsrId = row.userId
        for (let key in row) {
          if (this.form.hasOwnProperty(key)) {
            this.form[key] = row[key];
          }
        }
        this.frontImg = row.frontImg
        this.backImg = row.backImg
        this.avatarUrl = row.avatar
        this.certificateImg = row.certificateImg
        this.projectDetail = row.projectDetail
        this.loc.longitude=row.longitude
        this.loc.latitude=row.latitude
      }
    },
    openMapDia() {
      this.initAMap();
      this.openMap = true
    },
    deletePic(i) {
      this.upImage.splice(i, 1)
    },
    handleChangePic(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
        this.certificateImg = fileList
      }
    },
    handleChangeFont(res, fileList) {
      this.frontImg = res.result[0];
    },
    handleChangeBack(res, fileList) {
      this.backImg = res.result[0];
    },
    // handleAvatarSuccess(res, file) {
    //   this.imageUrl.push(res.data.result[0])
    //   console.log(this.imageUrl)
    // },
    handleAvatar(res, file) {
      this.avatarUrl = res.result[0];
    },
    addExperience(val) {
      this.projectDetail.push({
        startTime: "",
        endTime: "",
        content: "",
        projectName: ""
      })
    },
    deleteExperience(index) {
      this.projectDetail.splice(index, 1)
    },
    submitTalent() {
      const data = {
        ...this.form,
        projectDetail: this.projectDetail,
        frontImg: this.frontImg,
        backImg: this.backImg,
        avatar: this.avatarUrl,
        certificateImg: [this.certificateImg],
        longitude: this.loc.longitude,
        latitude: this.loc.latitude
      }
      this.$api.talentInsertPcTalent(data).then(res => {
        if (res == 1) {
          this.$emit('addStatus', 1);
          this.$message.success("添加成功！")
          this.addTalentDialog = false
        }
      })
    },
    editTalent() {
      const data = {
        ...this.form,
        projectDetail: this.projectDetail,
        frontImg: this.frontImg,
        backImg: this.backImg,
        avatar: this.avatarUrl,
        certificateImg: this.certificateImg,
        longitude: this.loc.longitude,
        latitude: this.loc.latitude,
        userId:this.editUsrId
      }
      this.$api.talentUpdateTalent(data).then(res => {
        if (res == 1) {
          this.$emit('addStatus', 1);
          this.$message.success("编辑成功！")
          this.addTalentDialog = false
        }
      })
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped lang="less">
#container {
  width: 100%;
  height: 500px;
}

::v-deep .el-dialog__body {
  padding: 0px 20px !important;
}

.mapBox {
  position: relative;

  .searchBox {
    position: absolute;
    z-index: 111;
    top: 10px;
    left: 10px;
  }
}

.search-result {
  width: 100%;
  max-height: 300px;
  overflow-y: scroll;
  background-color: #fff;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.0600);
  box-sizing: border-box;

  .result-item {
    width: 100%;
    cursor: pointer;
    border-bottom: 2px solid #eee;
    padding: 10px 12px;

    .area-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      height: 20px;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      line-height: 20px;
    }

    .area-address {
      color: rgba(0, 0, 0, 0.4500);
      font-size: 12px;
      line-height: 18px;
    }
  }
}

.avatar-uploader {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.content {
  width: 90%;
  margin-top: 10px;
  display: flex;
  align-items: center;

  .el-input, .el-select {
    margin-right: 30px;
  }
}

.box-card {
  min-height: 200px;

}
</style>